package com.bright.ghj.overt.service.impl;

import com.bright.ghj.overt.constant.RocketConstant;
import com.bright.ghj.overt.mq.MQProduceService;
import com.bright.ghj.overt.pojo.command.ImportAccessCommand;
import com.bright.ghj.overt.pojo.po.primary.MqMessage;
import com.bright.ghj.overt.pojo.vo.AsyncTaskResultVO;
import com.bright.ghj.overt.service.AccessImportService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @Author hxj
 * @Date 2024/2/27 17:31
 * @Description
 */
@Component
@Slf4j
@RequiredArgsConstructor
@ConditionalOnBean(value = RocketMQTemplate.class)
@Qualifier("MQAccessImport")
public class MQAccessImportServiceImpl implements AccessImportService<AsyncTaskResultVO> {

    private final MQProduceService mqProduceService;

    private final ObjectMapper objectMapper;

    @Override
    public List<AsyncTaskResultVO> startImport(ImportAccessCommand command, File accessFile, String userName) {
        String data;
        List<AsyncTaskResultVO> result = new ArrayList<>();
        AsyncTaskResultVO asyncTaskResultVO = new AsyncTaskResultVO();
        String keyword = userName + "_" + UUID.randomUUID();
        asyncTaskResultVO.setKeyword(keyword);

        try {
            data = objectMapper.writeValueAsString(command);

            MqMessage<String> mqMessage = new MqMessage<>();

            mqMessage.setKeyword(keyword);
            mqMessage.setTopicType(RocketConstant.TOPIC_ACCESS_IMPORT);
            mqMessage.setUsername(userName);
            mqMessage.setReadFlag(false);
            mqMessage.setConsumerFlag(RocketConstant.CONSUMER_FLAG_TODO);
            mqMessage.setData(data);
            mqMessage.setFile(accessFile);

            mqProduceService.sendMessage(mqMessage);
            asyncTaskResultVO.setIsSubmitTask(true);
        } catch (Exception e) {
            e.printStackTrace();
            asyncTaskResultVO.setIsSubmitTask(false);
            asyncTaskResultVO.setNoSubmitIllustrate("执行出错：" + e.getMessage());
        }



        result.add(asyncTaskResultVO);
        return result;
    }
}
